<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\Admin;

use Model\Admin\CategoryModel as CategoryModel;
use Model\Admin\ModelModel as ModelModel;
use Core\Db\Db as Db;

/**
 * 分类管理
 * @author LazyPHP
 * @version 1.0
 */
class Category extends Common {

    private $tree = '', $li = 1, $selected;
    private $thumb = array(
        'field_name' => 'thumb',
        'name' => '略缩图',
        'type' => 'thumb'
    );

    /**
     * 分类列表
     */
    public function index() {
        $db = $this->db('category pc');
        $tree = CategoryModel::outPutListCate();
        $this->assign('tree', $tree);
        $this->display();
    }

    /**
     * 添加分类
     */
    public function add() {
        //添加对应的下层分类
        if (isset($_GET['id'])) {
            $id = $this->g('id');
            $findCate = CategoryModel::listCategory($id);
            $this->determineSqlExecResult($findCate, '不存在该分类');

            $tree = CategoryModel::getSelectCate($findCate['id']);
            //输出模型(下拉框)
            //此处适用于初始化时，沿用父级分类的模型
            $listModel = ModelModel::getModel();
            $modelOption = $this->getSelectModel($listModel, $findCate['model_id']);
            $this->assign('modelOption', $modelOption);
            $this->assign('title', "添加‘{$findCate['cate_name']}’的下层分类");
        } else {
            $tree = CategoryModel::getSelectCate();
            $listModel = ModelModel::getModel();
            $modelOption = $this->getSelectModel($listModel);
            $this->assign('modelOption', $modelOption);
            $this->assign('title', '添加新分类');
        }
        $this->assign('thumb', $this->thumb);
        $this->assign('tree', $tree);
        $actionUrl = "/?g=Admin&m=Category&a=insert";
        $this->assign('actionUrl', $actionUrl);
        $this->display();
    }

    /**
     * 插入分类
     */
    public function insert() {
        $data['parent_id'] = is_numeric($_POST['parent_id']) ? $_POST['parent_id'] : '请选择分类级别';
        $data['model_id'] = $this->is_p('model_id', '请选择分类模型');
        $data['cate_name'] = $this->is_p('cate_name', '请填写分类名称');
        $data['aliases'] = $this->p('aliases');
        $data['keyword'] = $this->p('keyword');
        $data['description'] = $this->p('description');
        $data['thumb'] = $this->p('thumb');
        $data['is_nav'] = is_numeric($_POST['is_nav']) ? $_POST['is_nav'] : '请选择是否导航';
        $data['listsort'] = $this->p('listsort');
        $db = $this->db('category');
        $addResult = $db->add($data);
        $this->determineSqlExecResult($addResult, '添加分类出错!');

        //更新对应树的分类
        $this->setChild();

        //获取model并设置URL
        $this->setUrl($data['model_id'], $addResult);
        $this->clearUploadRecord();
        $this->success('成功添加分类!', '/?g=Admin&m=Category&a=index');
    }

    /**
     * 初始化编辑页面
     */
    public function edit() {
        $id = $this->is_g('id', '请选择您要编辑的分类');
        $findCate = CategoryModel::listCategory($id);
        $this->determineSqlExecResult($findCate, '不存在该分类');
        foreach ($findCate as $key => $value) {
            $this->assign($key, $value);
        }

        //输出分类(下拉框)
        $tree = CategoryModel::getSelectCate($findCate['parent_id']);
        $this->assign('tree', $tree);

        //输出模型(下拉框)
        $listModel = ModelModel::getModel();
        $modelOption = $this->getSelectModel($listModel, $findCate['model_id']);
        $this->assign('modelOption', $modelOption);

        $this->thumb['value'] = $findCate['thumb'];
        $this->assign('thumb', $this->thumb);
        $actionUrl = "/?g=Admin&m=Category&a=update&id={$id}";
        $this->assign('actionUrl', $actionUrl);
        $this->assign('title', '编辑分类');
        $this->display('Category_add');
    }

    /**
     * 进行分类更新
     */
    public function update() {
        $data['id'] = $this->is_g('id', '请选择您要编辑的分类');
        $data['parent_id'] = is_numeric($_POST['parent_id']) ? $_POST['parent_id'] : '请选择分类级别';
        if ($data['id'] == $data['parent_id']) {
            $this->error('不能选择本身分类作为级别');
        }
        $data['model_id'] = $this->is_p('model_id', '请选择分类模型');
        $data['cate_name'] = $this->is_p('cate_name', '请填写分类名称');
        $data['aliases'] = $this->p('aliases');
        $data['keyword'] = $this->p('keyword');
        $data['description'] = $this->p('description');
        $data['thumb'] = $this->p('thumb');
        $data['is_nav'] = is_numeric($_POST['is_nav']) ? $_POST['is_nav'] : '请选择是否导航';
        $data['listsort'] = $this->p('listsort');

        //更新分类
        $db = $this->db('category');
        $updateResult = $db->where('id = :id')->save($data);
        $this->determineSqlExecResult($updateResult, '编辑分类失败！');

        //更新对应树的分类
        $this->setChild();

        //获取model并设置URL
        $this->setUrl($data['model_id'], $data['id']);
        $this->clearUploadRecord();
        $this->success('分类编辑成功！', '/?g=Admin&m=Category&a=index');
    }

    /**
     * 删除分类
     */
    public function delete() {
        $data['id'] = $this->is_g('id', '请选择您要编辑的分类');
        $existCate = CategoryModel::getCategory($data['id']);

        $this->determineSqlExecResult($existCate, '不存在此分类');
        $db = $this->db('category');
        $db->startTrans();
        //删除对应的
        $deleteResult = $db->where('id = :id')->delete($data);
        if ($deleteResult == false) {
            $db->rollBack();
            $db->error('删除分类失败');
        }
        $existChildCate = CategoryModel::getCategory($data['id'], 'parent_id');
        if ($existChildCate != false) {
            $move['parent_id'] = '0';
            $moveResult = $db->where("parent_id = {$data['id']}")->save($move);
            if ($moveResult == false) {
                $db->rollBack();
                $this->error('迁移子类时失败');
            }
        }
        $db->commit();
        $this->success('成功删除分类!', '/?g=Admin&m=Category&a=index');
    }

    /**
     * @todo 此方法需要进行改进的！！
     */
    public function upload() {
        parent::upload();
    }

    /**
     * 进行排序
     */
    public function listsort() {
        $listsort = $this->is_p('listsort', '您没有提交值');

        $db = $this->db('category');
        foreach ($listsort as $key => $value) {
            $db->where('id = :id')->save(array('id' => $key, 'listsort' => $value));
        }
        $this->success('排序已更新!', '/?g=Admin&m=' . MODULE . '&a=index');
    }

    /**
     * 用于分类模型的表单
     * @param type $array 模型数组
     * @param type $modelId 模型ID
     * @return string 返回预设好的表单
     */
    private function getSelectModel($array, $modelId = '') {
        $option = '';
        foreach ($array as $key => $value) {
            if ($value['id'] == $modelId) {
                $option .= '<option value="' . $value['id'] . '" selected="selected" >' . $value['name'] . '</option>';
            } else {
                $option .= '<option value="' . $value['id'] . '" >' . $value['name'] . '</option>';
            }
        }
        return $option;
    }

    /**
     * 设置分类URL
     * @param int $modelId 模型ID
     * @param int $catid 分类ID
     * @return string 返回URL
     */
    protected function setUrl($modelId, $catid) {
        switch ($modelId) {
            //执行单页数据插入
            case '1':
                $getCate = CategoryModel::getCategory($catid);
                $this->determineSqlExecResult($getCate, '获取分类信息出错');
                //此处不做模型检查了，单页模型不存在，则会出错！
                $db = $this->db('page');

                $existPageContent = $db->where('id =:id')->find(array('id' => $catid));
                $page['id'] = $catid;
                $page['url'] = $data['url'] = "/Page-view-id-{$catid}";
                $page['title'] = $getCate['cate_name'];
                $page['thumb'] = $getCate['thumb'];
                $page['keyword'] = $getCate['keyword'];
                $page['description'] = $getCate['description'];
                if (empty($existPageContent)) {
                    $page['status'] = '1';
                    $page['createtime'] = time();
                    $addPageContentResult = $db->add($page);
                    $this->determineSqlExecResult($addPageContentResult, '添加单页内容时出错');
                } else {
                    $updatePageContentResult = $db->save($page);
                    $this->determineSqlExecResult($addPageContentResult, '同步单页内容时出错');
                }

                break;
            //执行外部链接插入操作
            case '-1':
                $data['url'] = $this->p('url', FALSE);
                break;
            default:
                //获取model并设置URL
                $getModel = ModelModel::getModel($modelId);
                $this->determineSqlExecResult($getModel, '不存在此模型');
                $data['url'] = "/{$getModel['model_name']}-list-id-{$catid}";
        }
        $data['id'] = $catid;
        $db = $this->db('category');
        $updateUrl = $db->where('id =:id')->save($data);
    }

    /**
     * 添加子类
     */
    private function setChild() {
        $db = $this->db('category');
        $topCat = $db->where('parent_id = 0')->select();
        foreach ($topCat as $key => $value) {
            $child = explode(',', CategoryModel::listChildId($value['id']));
            CategoryModel::$tree = '';

            foreach ($child as $_key => $_value) {
                $updateChild = $db->where('id = :id')->save(array('id' => $_value, 'child' => CategoryModel::listChildId($_value)));
                CategoryModel::$tree = '';
            }
        }
    }

}
